package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	equ := "1+x=2"
	res := solveEquation(equ)
	fmt.Println(res)
}

func solveEquation(equation string) string {
	leftX, rightX := 0, 0     //左右两侧x个数
	leftSum, rightSum := 0, 0 //左右两侧除x外所有数的和
	strs := strings.Split(equation, "=")
	leftX, leftSum = parse(strs[0])
	//fmt.Println(leftX, leftSum)
	rightX, rightSum = parse(strs[1])
	//fmt.Println(rightX, rightSum)
	x := leftX - rightX
	val := rightSum - leftSum
	if x == 0 {
		if val == 0 {
			return "Infinite solutions"
		} else {
			return "No solution"
		}
	}
	return "x=" + strconv.Itoa(val/x)
}

//返回等式一边x个数和其他项的和
func parse(str string) (x, sum int) {
	chs := []byte(str)
	cur := ""
	for i, ch := range chs {
		if i > 0 && (ch == '+' || ch == '-') {
			if cur[len(cur)-1] == 'x' {
				if cur == "x" || cur == "+x" {
					x++
				} else if cur == "-x" {
					x--
				} else {
					num, _ := strconv.Atoi(cur[:len(cur)-1])
					x += num
				}
			} else {
				num, _ := strconv.Atoi(cur)
				sum += num
			}
			//fmt.Println(cur)
			cur = ""
		}
		cur += string(ch)
	}

	//最后一项
	if cur[len(cur)-1] == 'x' {
		if cur == "x" || cur == "+x" {
			x++
		} else if cur == "-x" {
			x--
		} else {
			num, _ := strconv.Atoi(cur[:len(cur)-1])
			x += num
		}
	} else {
		num, _ := strconv.Atoi(cur)
		sum += num
	}
	//fmt.Println(cur)

	return
}
